﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Drawing;

namespace Adartse.Sharepoint.WebPartEditors
{
    public class ListItemEditor: EditorPart
    {
        private DropDownList _ddlLists;
        private DropDownList _ddlViews;
        private TextBox _tbxEditor;
        private CheckBox _chkViews;  
        private TextBox _tbxItems;
        private TextBox _tbxHeader;
        private TextBox _tbxID;
        private TextBox _tbxClass;
        private CheckBox _chkID;
        private CheckBox _chkClass;

        private TextBox _tbxItemParameter;
        private CheckBox _chkEnablePreviousNext;

        private bool _GotPrevius;
        private bool _GotNext;

        private TextBox _tbxPreviusText;
        private TextBox _tbxNextText;

        private TextBox _tbxFolderParameter;
        private CheckBox _chkEnableFolderParameter;

        private TextBox _tbxEmptyTemplate;


        public ListItemEditor()
        {
            this.Title = "Configuration";
        }

        public override bool ApplyChanges()
        {
            this.EnsureChildControls();
            AWPListItem wp = (AWPListItem)this.WebPartToEdit;

            wp.ListName = _ddlLists.SelectedValue;
            wp.HtmlContent = _tbxEditor.Text;
            wp.ContainterID = _tbxID.Text;
            wp.ContainerClass = _tbxClass.Text;
            wp.IsIDEnabled = _chkID.Checked;
            wp.IsClassEnabled = _chkClass.Checked;
            wp.HeaderContent = _tbxHeader.Text;
            wp.IsByView = _chkViews.Checked;
            wp.ViewName = _ddlViews.SelectedValue;

            wp.ItemParameter = _tbxItemParameter.Text;
            wp.EnablePreviusNextLinks = _chkEnablePreviousNext.Checked;
            
            wp.FieldList = ValidateFields(_tbxEditor.Text, new Guid(_ddlLists.SelectedValue));
            wp.GotNext = _GotNext;
            wp.GotPrevious = _GotPrevius;
            wp.PreviusText = _tbxPreviusText.Text;
            wp.NextText = _tbxNextText.Text;

            wp.FolderParameter = _tbxFolderParameter.Text;
            wp.EnableFolderParameter = _chkEnableFolderParameter.Checked ;

            wp.EmptyTemplate = _tbxEmptyTemplate.Text;
            
            return true;
        }

        public override void SyncChanges()
        {
            this.EnsureChildControls();
            AWPListItem wp = (AWPListItem)this.WebPartToEdit;

            _ddlLists.SelectedValue = wp.ListName;
            _tbxEditor.Text = wp.HtmlContent;
            _tbxHeader.Text = wp.HeaderContent;

            _tbxID.Text = wp.ContainterID;
            _tbxClass.Text = wp.ContainerClass;
            _chkID.Checked = wp.IsIDEnabled;
            _chkClass.Checked = wp.IsClassEnabled;

            _tbxItemParameter.Text = wp.ItemParameter;
            _chkEnablePreviousNext.Checked = wp.EnablePreviusNextLinks;

            _tbxNextText.Text = wp.NextText;
            _tbxPreviusText.Text = wp.PreviusText;

            _tbxFolderParameter.Text = wp.FolderParameter;
            _chkEnableFolderParameter.Checked = wp.EnableFolderParameter;

            _chkViews.Checked = wp.IsByView;
            if (wp.IsByView)
                _ddlViews.SelectedValue = wp.ViewName;

            _tbxEmptyTemplate.Text = wp.EmptyTemplate;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _ddlLists = new DropDownList();
            _tbxEditor = new TextBox();
            _tbxID = new TextBox();
            _tbxClass = new TextBox();
            _chkID = new CheckBox();
            _chkClass = new CheckBox();
            _tbxItems = new TextBox();
            _tbxHeader = new TextBox();

            _ddlViews = new DropDownList();
            _chkViews = new CheckBox();

            _tbxItemParameter = new TextBox();
            _chkEnablePreviousNext = new CheckBox();
            _tbxPreviusText = new TextBox();
            _tbxNextText = new TextBox();

            _tbxFolderParameter = new TextBox();
            _chkEnableFolderParameter = new CheckBox();

            _tbxEmptyTemplate = new TextBox();
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                _ddlLists.ID = "ddlListNames";
                _ddlLists.Width = new Unit(100, UnitType.Percentage);
                _ddlLists.AutoPostBack = true;
                _ddlLists.EnableViewState = true;

                _ddlViews.ID = "ddlViews";
                _ddlViews.Width = new Unit(75, UnitType.Percentage);
                _ddlViews.EnableViewState = true;

                _tbxItems.ID = "lbxItems";
                _tbxItems.Width = new Unit(100, UnitType.Percentage);
                _tbxItems.Height = new Unit(200);
                _tbxItems.EnableViewState = true;
                _tbxItems.TextMode = TextBoxMode.MultiLine;
                _tbxItems.ReadOnly = true;

                _chkID.ID = "chkID";
                _chkID.Text = "ID";
                _chkID.EnableViewState = true;

                _tbxID.ID = "tbxID";
                _tbxID.EnableViewState = true;

                _chkClass.ID = "chkClass";
                _chkClass.Text = "Class";
                _chkClass.EnableViewState = true;

                _tbxClass.ID = "tbxClass";
                _tbxClass.EnableViewState = true;

                _tbxItemParameter.ID = "tbxItemParameter";
                _tbxItemParameter.EnableViewState = true;
                _tbxItemParameter.Width = new Unit(100, UnitType.Percentage);

                _tbxHeader.ID = "tbxHeaderContent";
                _tbxHeader.Width = new Unit(100, UnitType.Percentage);
                _tbxHeader.Height = new Unit(60);
                _tbxHeader.TextMode = TextBoxMode.MultiLine;
                _tbxHeader.EnableViewState = true;

                _tbxEditor.ID = "tbxEditor";
                _tbxEditor.Width = new Unit(100, UnitType.Percentage);
                _tbxEditor.Height = new Unit(200);
                _tbxEditor.TextMode = TextBoxMode.MultiLine;


                _chkViews.ID = "chkViews";
                _chkViews.Text = "By View:";
                _chkViews.EnableViewState = true;
                _chkViews.AutoPostBack = true;

                _chkEnablePreviousNext.ID = "chkEnablePreviousNext";
                _chkEnablePreviousNext.Text = "Enable Next and Previous anchors";
                _chkEnablePreviousNext.EnableViewState = true;

                _tbxNextText.ID = "tbxNextText";
                _tbxNextText.EnableViewState = true;
                _tbxNextText.Width = new Unit(100, UnitType.Percentage);

                _tbxPreviusText.ID = "tbxPreviusText";
                _tbxPreviusText.EnableViewState = true;
                _tbxPreviusText.Width = new Unit(100, UnitType.Percentage);

                _tbxFolderParameter.ID = "tbxFolderParameter";
                _tbxFolderParameter.EnableViewState = true;
                _tbxFolderParameter.Width = new Unit(100, UnitType.Percentage);

                _chkEnableFolderParameter.ID = "chkEnableFolderParameter";
                _chkEnableFolderParameter.Text = "Enable QueryString Folder Parameter";
                _chkEnableFolderParameter.EnableViewState = true;
                _chkEnableFolderParameter.AutoPostBack = true;

                _tbxEmptyTemplate.ID = "tbxEmptyTemplate";
                _tbxEmptyTemplate.EnableViewState = true;
                _tbxEmptyTemplate.Width = new Unit(100, UnitType.Percentage);
                _tbxEmptyTemplate.Height = new Unit(200, UnitType.Pixel);
                _tbxEmptyTemplate.TextMode = TextBoxMode.MultiLine;

                Controls.Add(_ddlLists);
                Controls.Add(_tbxItems);
                Controls.Add(_chkID);
                Controls.Add(_tbxID);
                Controls.Add(_chkClass);
                Controls.Add(_tbxClass);
                Controls.Add(_tbxHeader);
                Controls.Add(_tbxEditor);

                Controls.Add(_ddlViews);
                Controls.Add(_chkViews);

                Controls.Add(_tbxItemParameter);
                Controls.Add(_chkEnablePreviousNext);

                Controls.Add(_tbxNextText);
                Controls.Add(_tbxPreviusText);

                Controls.Add(_chkEnableFolderParameter);
                Controls.Add(_tbxFolderParameter);

                Controls.Add(_tbxEmptyTemplate);

                if (_ddlLists.Items.Count == 0)
                {
                    FillData();
                }
            }
            catch (Exception ex)
            {
                Controls.Add(new LiteralControl(ex.ToString()));
            }
        }

        private void FillData()
        {
            _ddlLists.Items.AddRange(GetLists());
        }

        protected override void OnPreRender(EventArgs e)
        {
            Guid guid = Guid.Empty;
            if (!string.IsNullOrEmpty(_ddlLists.SelectedValue))
                guid = new Guid(_ddlLists.SelectedValue);

            if (!guid.Equals(Guid.Empty))
            {
                SPList list = SPContext.Current.Web.Lists.GetList(guid, false);
                _tbxItems.Text = string.Empty;
                _ddlViews.Items.Clear();
                _ddlViews.Items.AddRange(GetViews(list));
                _tbxItems.Text = string.Join(Environment.NewLine, GetListItem(list) );

                if (_chkViews.Checked)
                {
                    _ddlViews.Enabled = true;
                    _ddlViews.BackColor = Color.White;
                }
                else
                {
                    _ddlViews.Enabled = false;
                    _ddlViews.BackColor = Color.FromKnownColor(KnownColor.InactiveCaption);
                }

                if (list.Folders.Count > 0)
                {
                    _chkEnableFolderParameter.Enabled = true;
                    if (_chkEnableFolderParameter.Checked)
                    {
                        _tbxFolderParameter.Enabled = true;
                        _tbxFolderParameter.BackColor = Color.White;
                    }
                    else
                    {
                        _tbxFolderParameter.Enabled = false;
                        _tbxFolderParameter.BackColor = Color.FromKnownColor(KnownColor.InactiveCaption);
                    }
                }
                else
                {
                    _tbxFolderParameter.Enabled = false;
                    _chkEnableFolderParameter.Enabled = false;
                }
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Available List/Galleries:");
            writer.RenderEndTag();
            writer.WriteBreak();
            //List Control
            _ddlLists.RenderControl(writer);
            writer.WriteBreak();
            //Views
            _chkViews.RenderControl(writer);
            writer.WriteEncodedText(" ");
            _ddlViews.RenderControl(writer);
            writer.WriteBreak();
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Fields:");
            writer.RenderEndTag();
            writer.WriteBreak();
            //Items
            _tbxItems.RenderControl(writer);
            writer.WriteBreak();
            //Tittle
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Container Tags:");
            writer.RenderEndTag();
            writer.WriteBreak();
            //Container ID
            _chkID.RenderControl(writer);
            _tbxID.RenderControl(writer);

            _chkClass.RenderControl(writer);
            _tbxClass.RenderControl(writer);
            writer.WriteBreak();
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("QueryString Item Parameter");
            writer.RenderEndTag();
            writer.WriteBreak();
            //Item Parameter
            _tbxItemParameter.RenderControl(writer);
            writer.WriteBreak();
            //Item Parameter
            _chkEnableFolderParameter.RenderControl(writer);
            writer.WriteBreak();
            //Folder Parameter
            _tbxFolderParameter.RenderControl(writer);
            writer.WriteBreak();
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Header Template");
            writer.RenderEndTag();
            //Header Template
            _tbxHeader.RenderControl(writer);
            writer.WriteBreak();
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Item Template");
            writer.RenderEndTag();
            //Editor Template
            _tbxEditor.RenderControl(writer);
            writer.WriteBreak();
            //Enable Next Pievious
            _chkEnablePreviousNext.RenderControl(writer);
            writer.WriteBreak();
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Previus Anchor Text");
            writer.RenderEndTag();
            //Editor Template
            _tbxPreviusText.RenderControl(writer);
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Next Anchor Text");
            writer.RenderEndTag();
            //Editor Template
            _tbxNextText.RenderControl(writer);
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Empty Template");
            writer.RenderEndTag();
            //Editor Template
            _tbxEmptyTemplate.RenderControl(writer);
            
            
            if (!Page.IsPostBack)
                FillData();
        }

        private ListItem[] GetLists()
        {
            List<ListItem> li = new List<ListItem>();
            foreach (SPList list in SPContext.Current.Web.Lists)
                li.Add(new ListItem(list.Title, list.ID.ToString()));

            return li.ToArray();
        }

        private string[] GetListItem(SPList list)
        {
            List<string> li = new List<string>();
            if (list != null)
            {
                SPFieldCollection fields = list.Fields;
                foreach (SPField field in fields)
                {
                    li.Add((string.Format("{0} [{1}]", field.Title, field.InternalName)));
                }
            }
            return li.ToArray();
        }

        private ListItem[] GetViews(SPList list)
        {
            List<ListItem> li = new List<ListItem>();
            if (list != null)
            {
                SPViewCollection views = list.Views;
                foreach (SPView view in views)
                {
                    li.Add(new ListItem(view.Title, view.ID.ToString()));
                }
            }
            return li.ToArray();
        }

        private Dictionary<string, string> ValidateFields(string template, Guid ListName)
        {
            Dictionary<string, string> keys = new Dictionary<string, string>();
            try
            {

                SPList list = SPContext.Current.Web.Lists.GetList(ListName, true); ;
                foreach (SPField field in list.Fields)
                {
                    if (template.IndexOf(string.Format("[{0}]", field.InternalName)) >= 0)
                    {
                        if (keys.ContainsKey(string.Format("[{0}]", field.InternalName))) continue;
                        keys.Add(string.Format("[{0}]", field.InternalName), field.InternalName);
                    }                        
                }

                _GotPrevius = template.IndexOf("[Previus]") >= 0;
                _GotNext = template.IndexOf("[Next]") >= 0;
                    
            }
            catch
            {

            }
            return keys;
        }
    }
}
